﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.IColumnManagement;
using IntelligentAgriculture.Domain.Interface.Iridgepletype;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace IntelligentAgriculture.Services
{
	/// <summary>
	/// 羔羊断奶实现
	/// </summary>
	public class LambweaninginfoService: ILambweaninginfoService
	{
		/// <summary>
		/// 数据库操作接口
		/// </summary>
		private readonly ILambweaninginfoRepository _lambweaninginfoRepository;
		private readonly ILogger<LambweaninginfoService> _logger;
		private readonly AgricultureDbContext _db;
		private readonly IMapper _mapper;
		/// <summary>
		/// 养只档案
		/// </summary>
		private readonly ISheepFileModelRepository _shepFileModelRepository;
		/// <summary>
		/// 栋舍
		/// </summary>
		private readonly IridegRepository _iridegRepository;
		/// <summary>
		/// 栏位
		/// </summary>
		private readonly IColumnManRepository _columnManRepository;
		/// <summary>
		/// 转舍记录
		/// </summary>
		private readonly IPurchaseFormModelRepository _purchaseFormModelRepository;
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="lambweaninginfoRepository"></param>

		public LambweaninginfoService(ILambweaninginfoRepository lambweaninginfoRepository, ILogger<LambweaninginfoService> logger, IMapper mapper, IridegRepository iridegRepository, IColumnManRepository columnManRepository, AgricultureDbContext db, ISheepFileModelRepository sheepFileModelRepository, IPurchaseFormModelRepository purchaseFormModelRepository)
		{
			_lambweaninginfoRepository = lambweaninginfoRepository;
			_logger = logger;
			_mapper = mapper;
			_iridegRepository = iridegRepository;
			_columnManRepository = columnManRepository;
			_db = db;
			_shepFileModelRepository = sheepFileModelRepository;
			_purchaseFormModelRepository = purchaseFormModelRepository;
		}
		/// <summary>
		/// 获取羔羊断奶信息
		/// </summary>
		/// <returns></returns>
		public async Task<PageOutput<LambweaninginfoOutPut>> GetLambweaninginfos(LambWeaningInfoInPut input)
		{
			try
			{
				var lamlist = await _lambweaninginfoRepository.GetLambweaninginfos();
				var rilist = _iridegRepository.Showinfo();
				var collist=  _columnManRepository.GetShow();
				var quary = from a in lamlist
							join b in rilist
							on a.ToBuildingManageId equals b.RidgepoleId
							join c in collist
							on a.ToColumnManagementId equals c.ColumnManagementId
							select new LambweaninginfoOutPut
							{
								CreateName = a.CreateName,
								WeaningAge = a.WeaningAge,
								CreateTime = a.CreateTime,
								CurrentBuilding = a.CurrentBuilding,
								CurrentBuildingName = rilist.FirstOrDefault(c => c.RidgepoleId == a.CurrentBuilding).RidgepoleName,
								CurrentField = a.CurrentField,
								CurrentFieldName = collist.FirstOrDefault(d => d.ColumnManagementId == a.CurrentField).ColumnName,
								EarTag = a.EarTag,
								IsDel = a.IsDel,
								LambWeaningId = a.LambWeaningId,
								MammalianNumber = a.MammalianNumber,
								Parity = a.Parity,
								Sex = a.Sex,
								ToBuildingManageId = a.ToBuildingManageId,
								ToBuildingManageIdName = rilist.FirstOrDefault(c => c.RidgepoleId == a.ToBuildingManageId).RidgepoleName,
								ToColumnManagementId = a.ToColumnManagementId,
								ToColumnManagementIdName = collist.FirstOrDefault(d => d.ColumnManagementId == a.ToColumnManagementId).ColumnName,
								WeaningDate = a.WeaningDate,
								WeaningWeight = a.WeaningWeight,
								UpdateName = a.UpdateName,
								UpdateTime = a.UpdateTime
							};
				if(!string.IsNullOrEmpty(input.StrartDate))
				{
					quary = quary.Where(c => c.WeaningDate >= Convert.ToDateTime(input.StrartDate));
				}
				if(!string.IsNullOrEmpty(input.EndDate))
				{
					quary = quary.Where(c => c.WeaningDate < Convert.ToDateTime(input.EndDate).AddDays(1));
				}
				if(!string.IsNullOrEmpty(input.EarTag))
				{
					quary=quary.Where(c=>c.EarTag== input.EarTag);
				}
				if(input.StartMonthold>0)
				{
					quary = quary.Where(c => (DateTime.Now.Day - c.WeaningDate.Value.Day) >= input.StartMonthold);
				}
				if (input.EndMonthold > 0)
				{
					quary = quary.Where(c => (DateTime.Now.Day - c.WeaningDate.Value.Day) <= input.EndMonthold);
				}
				if(input.StartWeaningWeight>0)
				{
					quary = quary.Where(c => c.WeaningWeight >= input.StartWeaningWeight);
				}
				if (input.EndWeaningWeight >0)
				{
					quary = quary.Where(c => c.WeaningWeight <= input.EndWeaningWeight);
				}
				if (!string.IsNullOrEmpty(input.MammalianNumber))
				{
					quary = quary.Where(c => c.MammalianNumber == input.MammalianNumber);
				}
				var list = quary.OrderByDescending(c => c.CreateTime).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();
				var cook=_mapper.Map<List<LambweaninginfoOutPut>>(list);
				var result = new PageOutput<LambweaninginfoOutPut>()
				{
					TotalCount = quary.Count(),
					PageSize = input.PageSize,
					Data = cook
				};
				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError("获取羔羊断奶信息异常:" + ex.Message);
				throw;
			}
		}
		/// <summary>
		/// 羔羊断奶删除
		/// </summary>
		/// <param name="loginUserName"></param>
		/// <param name="ids"></param>
		/// <returns></returns>
		public async Task<int> DelLambweaninginfos(params string[] eartag)
		{
			try
			{
				string loginUserName = "admin";
				var result = await _lambweaninginfoRepository.DelLambweaninginfos(loginUserName, eartag);
				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError("羔羊断奶删除异常:" + ex.Message);
				throw;
			}
		}
		/// <summary>
		/// 羔羊断奶添加
		/// </summary>
		/// <param name="lambweaninginfo"></param>
		/// <returns></returns>
		public async Task<int> AddLambweaninginfo(List<Lambweaninginfo> lambweaninginfo)
		{
			using(var tran = _db.Database.BeginTransaction())
			{
				try
				{
					//羊只档案接口
					var sheepfile = await _shepFileModelRepository.GetSheepfilemodels();
					//设置公共属性
					lambweaninginfo.ForEach(c =>
					{
						c.MammalianNumber=sheepfile.FirstOrDefault(d=>d.EarTag==c.EarTag).MatherEarNum;
						int weaningAge = DateTime.Now.Day - c.WeaningDate.Value.Day;
						c.WeaningAge = Math.Abs(weaningAge);
						c.CreateName = "admin";
						c.CreateTime = DateTime.Now;
						c.IsDel = false;
						c.UserId = 1;
						c.Parity = 1;
					});
					var result = await _lambweaninginfoRepository.AddLambweaninginfo(lambweaninginfo);

					
					// 构建 羊只转舍 列表
					var tasks = lambweaninginfo.Select(async item =>
					{
						var id = YitIdHelper.NextId().ToString();
						var sheepRescission = new Sheeprescission
						{
							SheepRescissionDate = DateTime.Now,
							EarTag = item.EarTag,
							RoundType = 10,
							OutBuildingManageId = item.CurrentBuilding,
							OutColumMangementId = item.CurrentField,
							ToBuildingManageId = item.ToBuildingManageId,
							ToColumMangementId = item.ToColumnManagementId,
							SheepType = 3,
							Variety = sheepfile.FirstOrDefault(c => c.EarTag == item.EarTag)?.Variety,
							SheepRescissionSex = sheepfile.FirstOrDefault(c => c.EarTag == item.EarTag)?.SheepSex,
							CreateName = item.CreateName,
							CreateTime = DateTime.Now,
							UpdateName = item.CreateName,
							UpdateTime = DateTime.Now,
							DocumentNumber = id,
							Isdel = item.IsDel
						};

						await Task.Yield(); // 确保异步波长行为

						return sheepRescission;
					}).ToList();

					// 等待所有异步任务完成并获取结果
					var sheeprescissions = await Task.WhenAll(tasks);

					// 异步添加到转舍
					
					 await _purchaseFormModelRepository.AddPurchaseFormModel(sheeprescissions.ToList());
					//获取耳号
					var lameartag = lambweaninginfo.Select(c=>c.EarTag).ToList();
					var sheeplist = await _shepFileModelRepository.GetSheepfilemodels();
					//通过耳号查询档案获取档案
					var eag = sheeplist.Where(c => lameartag.Contains(c.EarTag)).ToList();
					//更新档案表
					eag.ForEach(c => {
						c.Growthstage = 2;
						c.ColumnId=lambweaninginfo.FirstOrDefault(d=>d.EarTag==c.EarTag).ToColumnManagementId;
						c.BuildingId = lambweaninginfo.FirstOrDefault(d => d.EarTag == c.EarTag).ToBuildingManageId;
						c.AblactationDate=lambweaninginfo.FirstOrDefault(d => d.EarTag == c.EarTag).WeaningDate;
					}) ;
					tran.Commit();
					return await _shepFileModelRepository.UpdateListSheepFileModel(eag);
					
					
				}
				catch (Exception ex)
				{
					_logger.LogError("羔羊断奶删除异常:" + ex.Message);
					throw;
				}
			}
           
        }
        /// <summary>
        /// 反填羔羊断奶
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Lambweaninginfo> DteilLambweaninginfo(string eartag)
        {
            try
            {
                var result = await _lambweaninginfoRepository.DteilLambweaninginfo(eartag);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError("反填羔羊断奶异常:" + ex.Message);
                throw;
            }
        }
		/// <summary>
		/// 修改羔羊断奶
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		/// <summary>
		public async Task<int> UpdateLambweaninginfo(Lambweaninginfo entity)
		{
			try
			{
				await _lambweaninginfoRepository.UpdateLambweaninginfo(entity);
				var lamupd=await _shepFileModelRepository.GetSheepfilemodels();
				var list = lamupd.FirstOrDefault(c => c.EarTag == entity.EarTag);
				list.ColumnId = entity.ToColumnManagementId;
				list.BuildingId = entity.ToBuildingManageId;
				return await _shepFileModelRepository.UpdaSheepFileModel(list);
			}
			catch (Exception ex)
			{
				_logger.LogError("修改羔羊断奶奶异常:" + ex.Message);
				throw;
			}
		}



	}
}
